package com.read;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.regex.*;

public class LogToDatabase {
    private static final String LOG_FILE_PATH = "/Users/yzw/Desktop/log-info-lat.log";
    private static final Pattern JSON_PATTERN = Pattern.compile("\\{.*?\\}");

    private static final String DB_URL = "jdbc:mysql://rm-uf62m311y3411pfo8so.mysql.rds.aliyuncs.com/gysets_test2?useSSL=false&useUnicode=yes&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "wjjh_root_2024";

    public static void main(String[] args) {
        List<CommuteSearchRequest> requests = parseLog(LOG_FILE_PATH);
        insertIntoDatabase(requests);
    }

    public static List<CommuteSearchRequest> parseLog(String filePath) {
        List<CommuteSearchRequest> resultList = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                Matcher matcher = JSON_PATTERN.matcher(line);
                if (matcher.find()) {
                    String json = matcher.group();
                    try {
                        CommuteSearchRequest request = objectMapper.readValue(json, CommuteSearchRequest.class);
                        resultList.add(request);
                    } catch (Exception e) {
                        System.err.println("JSON 解析失败: " + json);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultList;
    }

    public static void insertIntoDatabase(List<CommuteSearchRequest> requests) {
        String sql = "INSERT INTO commute_search_log (seconds, type, lon, lat, order_by) VALUES (?, ?, ?, ?, ?)";

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            for (CommuteSearchRequest request : requests) {
                pstmt.setInt(1, request.getSeconds());
                pstmt.setInt(2, request.getType());
                pstmt.setString(3, request.getLon());
                pstmt.setString(4, request.getLat());
                pstmt.setInt(5, request.getOrderBy());
                pstmt.addBatch();
            }
            pstmt.executeBatch();
            System.out.println("数据成功写入数据库！");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
